package cn.edu.hyit.zhao.utils;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;

import cn.edu.hyit.zhao.dao.ILogDAO;
import cn.edu.hyit.zhao.entity.Log;


/**
 * 日志工具类
 * 
 * @author Neko
 * @version 1.0
 * @date 2016-01-04
 * 
 */
public class LogUtils {

	/**
	 * 
	 * @param request
	 * @param type
	 *            日志类型,默认使用接入日志类型
	 */
	public static void saveLog(HttpServletRequest request, String type) {
		saveLog(request, null, type);
	}

	/**
	 * 
	 * @param request
	 * @param ex
	 *            异常信息
	 * @param type
	 *            日志类型,默认使用接入日志类型
	 */
	public static void saveLog(HttpServletRequest request, Exception ex,
			String type) {
		if (request != null) {
			String username = request.getParameter("username");
			Log log = new Log();
			log.setMethod(request.getMethod());
			log.setRemoteAddr(StringUtil.getRemoteAddr(request));
			log.setRequestUri(request.getRequestURI());
			log.setParams(request.getParameterMap());
			log.setUser(username == null ? "未知操作者" : username);
			log.setUserAgent(request.getHeader("user-agent"));
			log.setCreateTime(new Timestamp(System.currentTimeMillis()));
			if (ex == null) {
				// 默认日志类型为接入日志
				log.setType(type == null ? Log.TYPE_ACCESS : type);
			} else {
				log.setType(Log.TYPE_EXCEPTION);
			}
			// 异步保存日志
			new SaveLogThread(log, ex).start();
			;
		}
	}

	/**
	 * 保存日志线程
	 */
	private static class SaveLogThread extends Thread {
		private Log log;
		private Exception ex;

		private ILogDAO logDao = SpringContentHolder.getBean(ILogDAO.class);

		public SaveLogThread(Log log, Exception ex) {
			super(SaveLogThread.class.getSimpleName());
			this.log = log;
			this.ex = ex;
		}

		@Override
		public void run() {
			// 设置日志的异常信息
			log.setException(Exceptions.getStackTraceAsString(ex));
			// 若没有日志类型和异常，不保存日志
			if (StringUtil.validateNull(log.getType())
					&& StringUtil.validateNull(log.getException())) {
				return;
			}
			logDao.insert(log);
		}
	}
}
